package com.ljh.seckill.service.impl;

import com.ljh.seckill.entity.Order;
import com.ljh.seckill.entity.Resource;
import com.ljh.seckill.repository.OrderRepository;
import com.ljh.seckill.repository.ResourceRepository;
import com.ljh.seckill.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author grung
 * @Date 2021/2/22 17:45
 * @Version 1.0
 */

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ResourceRepository resourceRepository;


    @Override
    public Resource findResourceById(String resourceId) {
        return resourceRepository.findById(resourceId).get();
    }

    @Override
    public Order findOrderById(String orderId) {
        return orderRepository.findById(orderId).get();
    }

    /**
     * 创建订单
     * @param orderId
     * @param resourceId
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class,timeout = 30)
    public Order createOrder(String orderId, String resourceId) {
        //订单重复校验
        Order order = orderRepository.findById(orderId).orElse(null);
        if (null!=order){
            return order;
        }

        Resource resource = this.findResourceById(resourceId);
        order=new Order();
        order.setId(orderId);
        order.setOrderAmount(resource.getAmount());
        order.setOrderStatus("待支付");
        order.setCreateDate(new Date());
        order.setUpdateDate(new Date());
        order.setUserId("ljh");
        orderRepository.save(order);

        resource.setStock(resource.getStock()-1);
        resource.setUpdateDate(new Date());
        resourceRepository.save(resource);
        return order;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class,timeout = 30)
    public Boolean cancelOrder(String orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (null==order){
            return false;
        }

        if ("待支付".equals(order.getOrderStatus())){
            return false;
        }

        order.setOrderStatus("已取消");
        order.setUpdateDate(new Date());
        orderRepository.save(order);

        Resource resource = this.findResourceById(order.getResourceId());
        resource.setStock(resource.getStock()+1);
        resource.setUpdateDate(new Date());
        return true;
    }
}
